/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.audio.AudioPlayer;
import com.sun.speech.freetts.audio.SingleFileAudioPlayer;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class ConvertToSpeech {

    private AudioPlayer audioPlayer = null;
    private VoiceManager voiceManager=VoiceManager.getInstance();
    private Voice voice;
    private String text;
    private String voiceName;

    public ConvertToSpeech() {
        voiceManager = VoiceManager.getInstance();
        Voice[] voices = voiceManager.getVoices();
        for (int i = 0; i < voices.length; i++) {
            System.out.println("    " + voices[i].getName()
                    + " (" + voices[i].getDomain() + " domain)");
        }
    }

    public void toSpeech(String text) {
        this.text=text;
        voiceName = "kevin16";
        System.out.println("Using voice:" + voiceName);
        voiceManager = VoiceManager.getInstance();
        voice = voiceManager.getVoice(voiceName);
        if (voice == null) {
            System.err.println("Cannot find voice name:" + voiceName);
            System.exit(1);
        }
        voice.allocate();
        voice.speak(text);
        voice.deallocate();
    }

    public void convertSpeechIntoFile(String filePath)
    {
        try{
        voiceManager = VoiceManager.getInstance();
        voice = voiceManager.getVoice(voiceName);
        voice.allocate();
        audioPlayer=new SingleFileAudioPlayer(filePath, Type.WAVE);
        voice.setAudioPlayer(audioPlayer);
        voice.speak(text);
        voice.deallocate();
        audioPlayer.close();
        }
        catch(NullPointerException e)
        {
            JOptionPane.showMessageDialog(null, "First Convert the Text into Speech!!", "File Save...", JOptionPane.ERROR_MESSAGE);
        }
    }
}
